let currentPage = 1; // 当前页码，默认从第1页开始
const pageSize = 10; // 每页显示条数，可根据实际需求调整
$(document).ready(function() {
    
    // 审核状态映射
    const auditStatusMap = {
        1: '<span class="px-2 py-1 text-xs rounded-full bg-pending/10 text-pending">待审核</span>',
        2: '<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">审核通过</span>',
        3: '<span class="px-2 py-1 text-xs rounded-full bg-danger/10 text-danger">审核拒绝</span>',
        4: '<span class="px-2 py-1 text-xs rounded-full bg-warning/10 text-warning">再次审核</span>',
        31:'<span class="px-2 py-1 text-xs rounded-full bg-danger/10 text-danger">涉黄</span>',
        32:'<span class="px-2 py-1 text-xs rounded-full bg-danger/10 text-danger">涉政</span>',
        33:'<span class="px-2 py-1 text-xs rounded-full bg-danger/10 text-danger">广告</span>',
        34:'<span class="px-2 py-1 text-xs rounded-full bg-danger/10 text-danger">其他</span>',
    };

    
    
    
    /**
     * 获取筛选参数
     */
    function getFilterParams() {
        return {
            page: currentPage,
            pageSize: pageSize,
            claimStatus: $('#collectionClaimStatusFilter').val(),
            status: $('#collectionStatusFilter').val(),
            sort: $('#collectionSortFilter').val(),
            keyword: $('#collectionKeywordSearch').val().trim(),
            submitter: $('#collectionSubmitterSearch').val().trim(),
            startDate: $('#collectionStartDate').val(),
            endDate: $('#collectionEndDate').val()
        };
    }
    /**
     * 获取合集列表
     */
    async function fetchCollectionList(params) {
        try {
            // 构建查询字符串
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    queryParams.append(key, value);
                }
            });

            // 发起请求
            const response = await fetch(`/system/GetCollectionListForPage?${queryParams.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    // 根据实际需求添加认证信息
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.status/1 != 200) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            showToast(error.message || '获取媒体内容列表失败');
        }
    }

    /**
     * 渲染分页控件
     * @param {number} total - 总记录数
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页条数
     */
    function renderPagination(total, currentPage, pageSize) {
        const totalPages = Math.ceil(total / pageSize);
        const paginationContainer = $('#collectionPagination'); // 分页容器
        
        // 清空现有分页
        paginationContainer.empty();
        
        // 上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage - 1}" ${prevDisabled}>
                <i class="fa fa-angle-left"></i>
            </button>
        `);
        
        // 页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整显示范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
            paginationContainer.append(`
                <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        // 下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage + 1}" ${nextDisabled}>
                <i class="fa fa-angle-right"></i>
            </button>
        `);
        
        // 更新分页信息
        const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        const end = Math.min(currentPage * pageSize, total);
        $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
    }

    /**
     * 更新批量操作按钮状态
     */
    function updateBatchButtons() {
        const selectedCount = $('.record-checkbox:checked').length;
        const buttons = $('#collectionBatchClaimBtn, #collectionBatchApproveBtn, #collectionBatchRejectBtn, #collectionBatchReviewBtn');
        
        if (selectedCount > 0) {
            buttons.removeAttr('disabled');
        } else {
            buttons.attr('disabled', 'disabled');
        }
    }

    /**
     * 更新已选择数量显示
     */
    function updateSelectedCount() {
        const count = $('.record-checkbox:checked').length;
        $('#collectionSelectedCount').text(`已选择 ${count} 项`);

    }

    /**
     * 加载合集列表
     */
    function initTableData() {
        // 显示加载中状态
        $('#collectionTableBody').html('<tr><td colspan="9" class="text-center py-4">加载中...</td></tr>');
        
        // 获取筛选参数
        const params = getFilterParams();
        
        // 调用后端接口获取数据
        fetchCollectionList(params)
            .then(result => {
                renderTable(result.data.list);
                renderPagination(result.data.total, currentPage, pageSize);
                updateSelectedCount();
                updateBatchButtons();
            })
            .catch(error => {
                // console.error('加载数据失败:', error);
                $('#collectionTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
            });
    }



    // 渲染表格数据
    function renderTable(data) {
        const tableBody = $('#collectionTableBody');
        tableBody.empty();
        
        if (data.length === 0) {
            tableBody.append(`
                <tr>
                    <td colspan="9" class="px-5 py-10 text-center text-neutral-500">
                        <i class="fa fa-folder-open-o text-3xl mb-2"></i>
                        <p>没有找到匹配的合集数据</p>
                    </td>
                </tr>
            `);
            return;
        }
        
        data.forEach(item => {
            const isClaimed = item.claimed_status;
            const claimStatus = item.claimed_status/1==2 
                ? `<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">已认领</span>`
                : `<span class="px-2 py-1 text-xs rounded-full bg-neutral-100 text-neutral-500">未认领</span>`;
            
            const claimInfo = isClaimed 
                ? `审核员ID: ${item.claimed_by}<br>${formatDateTime(item.claimed_time)}`
                : '未认领';
            
            let operateButtons = '';
            if (item.audit_status/1 === 1 || item.audit_status/1 === 4) {
                operateButtons = `
                    <div class="flex space-x-1">
                        <button class="text-primary hover:text-primary/80 text-sm view-detail" data-id="${item.collection_id}">
                            <i class="fa fa-eye"></i>
                        </button>
                        ${!isClaimed ? `<button class="text-primary hover:text-primary/80 text-sm claim-collection" data-id="${item.collection_id}">
                            <i class="fa fa-hand-paper-o"></i>
                        </button>` : ''}
                        <button class="text-success hover:text-success/80 text-sm approve-collection" data-id="${item.collection_id}" ${!isClaimed ? 'disabled title="请先认领"' : ''}>
                            <i class="fa fa-check"></i>
                        </button>
                        <button class="text-danger hover:text-danger/80 text-sm reject-collection" data-id="${item.collection_id}" ${!isClaimed ? 'disabled title="请先认领"' : ''}>
                            <i class="fa fa-times"></i>
                        </button>
                        <button class="text-warning hover:text-warning/80 text-sm review-collection" data-id="${item.collection_id}" ${!isClaimed ? 'disabled title="请先认领"' : ''}>
                            <i class="fa fa-flag"></i>
                        </button>
                    </div>
                `;
            } else {
                operateButtons = `
                    <div class="flex space-x-1">
                        <button class="text-primary hover:text-primary/80 text-sm view-detail" data-id="${item.collection_id}">
                            <i class="fa fa-eye"></i>
                        </button>
                        <button class="text-neutral-400 text-sm" data-id="${item.collection_id}" disabled>
                            <i class="fa fa-check"></i>
                        </button>
                        <button class="text-neutral-400 text-sm" data-id="${item.collection_id}" disabled>
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                `;
            }
            
            tableBody.append(`
                <tr>
                    <td class="px-5 py-4">
                        <input type="checkbox" class="collection-item-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${item.collection_id}">
                    </td>
                    <td class="px-5 py-4 text-sm">${item.collection_id}</td>
                    <td class="px-5 py-4">
                        <div class="font-medium">${item.name}</div>
                    </td>
                    <td class="px-5 py-4 text-sm text-neutral-600 max-w-xs truncate">${item.description}</td>
                    <td class="px-5 py-4 text-sm">
                        <div>提交者: ${item.submit_user_id}</div>
                        <div class="text-neutral-500 text-xs">${formatDateTime(item.submit_time)}</div>
                    </td>
                    <td class="px-5 py-4">
                        <div>${claimStatus}</div>
                        <div class="text-neutral-500 text-xs mt-1">${claimInfo}</div>
                    </td>
                    <td class="px-5 py-4">${auditStatusMap[item.audit_status]}</td>
                    <td class="px-5 py-4 text-sm">${item.chk_num}</td>
                    <td class="px-5 py-4">${operateButtons}</td>
                </tr>
            `);
        });
    }
    
    // 日期时间格式化
    function formatDateTime(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        }).replace(/\//g, '-');
    }
    
    // 初始化复选框事件
    function initCheckboxEvents() {
        // 全选/取消全选
        $('#collectionSelectAll').change(function() {
            const isChecked = $(this).is(':checked');
            $('.collection-item-checkbox').prop('checked', isChecked);
            updateBatchButtons();
        });
        
        // 单个复选框事件
        $(document).on('change', '.collection-item-checkbox', function() {
            const allChecked = $('.collection-item-checkbox:checked').length === $('.collection-item-checkbox').length;
            $('#collectionSelectAll').prop('checked', allChecked);
            updateBatchButtons();
        });
    }
    
    // 更新批量操作按钮状态
    function updateBatchButtons() {
        const checkedCount = $('.collection-item-checkbox:checked').length;
        $('#collectionSelectedCount').text(`已选择 ${checkedCount} 项`);
        
        const hasChecked = checkedCount > 0;
        $('#collectionBatchClaimBtn').prop('disabled', !hasChecked);
        $('#collectionBatchApproveBtn').prop('disabled', !hasChecked);
        $('#collectionBatchRejectBtn').prop('disabled', !hasChecked);
        $('#collectionBatchReviewBtn').prop('disabled', !hasChecked);
    }
    
    // 初始化筛选按钮事件
    function initFilterEvents() {
        // 筛选按钮
        $('#collectionFilterBtn').click(function() {
            // 获取筛选条件
            const filters = {
                claimStatus: $('#collectionClaimStatusFilter').val(),
                auditStatus: $('#collectionStatusFilter').val(),
                sort: $('#collectionSortFilter').val(),
                keyword: $('#collectionKeywordSearch').val().trim(),
                submitter: $('#collectionSubmitterSearch').val().trim(),
                startDate: $('#collectionStartDate').val(),
                endDate: $('#collectionEndDate').val()
            };
            
            // 这里应该调用接口获取筛选后的数据
            console.log('筛选条件:', filters);
            showToast('正在筛选数据...', 'info');
            
            // 模拟筛选延迟
            setTimeout(() => {
                // 实际应用中应使用接口返回的数据
                initTableData();
                showToast('筛选完成', 'success');
            }, 500);
        });
        
        // 重置按钮
        $('#collectionResetBtn').click(function() {
            $('#collectionClaimStatusFilter').val('0');
            $('#collectionStatusFilter').val('');
            $('#collectionSortFilter').val('0');
            $('#collectionKeywordSearch').val('');
            $('#collectionSubmitterSearch').val('');
            $('#collectionStartDate').val('');
            $('#collectionEndDate').val('');
            
            // 重置表格数据
            initTableData();
        });
    }
    
    // 初始化操作按钮事件
    function initActionEvents() {
        // 查看详情
        $(document).on('click', '.view-detail', function() {
            const collectionId = $(this).data('id');
            showCollectionDetail(collectionId);
        });

        // 分页按钮点击事件
        $(document).on('click', '.pagination-btn', function() {
            const page = parseInt($(this).data('page'));
            if (!isNaN(page) && page !== currentPage) {
                currentPage = page;
                initTableData()
            }
        });
        
        // 认领合集
        $(document).on('click', '.claim-collection', function() {
            const collectionId = $(this).data('id');
            showClaimModal(collectionId);
        });
        
        // 审核通过
        $(document).on('click', '.approve-collection', function() {
            const collectionId = $(this).data('id');
            // showApproveModal(collectionId);
            batchOperate([collectionId], 'approve')
                .then(() => {
                    initTableData(); // 重新加载列表
                    showToast('批量通过成功', 'success');
                })
                .catch(error => {
                    // console.error('批量认领失败:', error);
                    showToast('批量通过失败，请重试', 'error');
                });
        });
        
        // 审核拒绝
        $(document).on('click', '.reject-collection', function() {
            const collectionId = $(this).data('id');
            showRejectModal([collectionId]);
        });
        
        // 标记复查
        $(document).on('click', '.review-collection', function() {
            const collectionId = $(this).data('id');
            // showReviewModal(collectionId);
            showReviewModal([collectionId])
        });
        
        // 关闭详情模态框
        $('#closeDetailModal, #closeDetailBtn').click(function() {
            $('#collectionDetailModal').removeClass('flex').addClass('hidden');
        });
    }
    
    // 显示合集详情
    async function showCollectionDetail(collectionId) {
        try {
            // 显示加载状态
            $('#collectionDetailContent').html(`
                <div class="flex justify-center items-center py-10">
                    <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
                    <span class="ml-2 text-neutral-600">加载中...</span>
                </div>
            `);
            $('#collectionDetailModal').removeClass('hidden').addClass('flex');

            // 调用接口获取真实数据
            const response = await fetch(`/system/getCollectionDetail?collectionId=${encodeURIComponent(collectionId)}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                showToast('获取详情失败', 'error');
            }

            const result = await response.json();
            if (result.status/1 != 0 || !result.data) {
                // throw new Error(result.message || '获取详情数据失败');
                showToast(result.message || '获取详情数据失败', 'error');
            }

            const detailData = result.data;
            
            // 渲染详情内容
            const detailHtml = `
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="md:col-span-2">
                        <div class="mb-6">
                            <h4 class="text-sm text-neutral-500 mb-1">合集ID</h4>
                            <p class="font-medium">${detailData.collection_id || '-'}</p>
                        </div>
                        
                        <div class="mb-6">
                            <h4 class="text-sm text-neutral-500 mb-1">合集名称</h4>
                            <p class="font-medium text-lg">${detailData.name || '-'}</p>
                        </div>
                        
                        <div class="mb-6">
                            <h4 class="text-sm text-neutral-500 mb-1">合集描述</h4>
                            <div class="bg-neutral-50 p-3 rounded-lg text-neutral-700">${detailData.description || '无描述信息'}</div>
                        </div>
                        
                        <div class="mb-6">
                            <h4 class="text-sm text-neutral-500 mb-1">包含内容 (共 ${detailData.item_count || 0} 项)</h4>
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-neutral-200">
                                    <thead>
                                        <tr>
                                            <th class="px-3 py-2 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">ID</th>
                                            <th class="px-3 py-2 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">类型</th>
                                            <th class="px-3 py-2 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">名称</th>
                                            <th class="px-3 py-2 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-neutral-200">
                                        ${detailData.items && detailData.items.length > 0 
                                            ? detailData.items.map(item => `
                                                <tr>
                                                    <td class="px-3 py-2 text-sm">${item.id || '-'}</td>
                                                    <td class="px-3 py-2 text-sm">${item.type || '-'}</td>
                                                    <td class="px-3 py-2 text-sm">${item.name || '-'}</td>
                                                    <td class="px-3 py-2 text-sm">
                                                        <button class="text-primary hover:text-primary/80 view-media-item" 
                                                                data-id="${item.id}" 
                                                                data-type="${item.type}">
                                                            查看
                                                        </button>
                                                    </td>
                                                </tr>
                                            `).join('')
                                            : `
                                                <tr>
                                                    <td colspan="4" class="px-3 py-4 text-sm text-center text-neutral-500">
                                                        无内容数据
                                                    </td>
                                                </tr>
                                            `
                                        }
                                        ${detailData.item_count > 5 && detailData.items && detailData.items.length >=5 
                                            ? `
                                                <tr>
                                                    <td colspan="4" class="px-3 py-2 text-sm text-center text-neutral-500">
                                                        还有 ${detailData.item_count - 5} 项内容未显示
                                                    </td>
                                                </tr>
                                            ` : ''
                                        }
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <div class="bg-neutral-50 p-4 rounded-lg mb-6">
                            <h4 class="text-sm font-medium mb-3">审核信息</h4>
                            
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">审核状态</div>
                                <div class="mt-1">${auditStatusMap[detailData.audit_status] || '未知状态'}</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">审核次数</div>
                                <div class="mt-1 text-sm">${detailData.chk_num || 0} 次</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">提交者</div>
                                <div class="mt-1 text-sm">${detailData.submit_user_id || '-'}</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">提交时间</div>
                                <div class="mt-1 text-sm">${detailData.submit_time ? formatDateTime(detailData.submit_time) : '-'}</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">认领状态</div>
                                <div class="mt-1">
                                    ${detailData.claimed_by 
                                        ? `<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">已认领</span>` 
                                        : `<span class="px-2 py-1 text-xs rounded-full bg-neutral-100 text-neutral-500">未认领</span>`
                                    }
                                </div>
                            </div>
                            
                            ${detailData.claimed_by ? `
                            <div class="mb-3">
                                <div class="text-xs text-neutral-500">认领人</div>
                                <div class="mt-1 text-sm">审核员ID: ${detailData.claimed_by}</div>
                            </div>
                            
                            <div>
                                <div class="text-xs text-neutral-500">认领时间</div>
                                <div class="mt-1 text-sm">${detailData.claimed_time ? formatDateTime(detailData.claimed_time) : '-'}</div>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
            
            $('#collectionDetailContent').html(detailHtml);
            $('#operateFromDetailBtn').data('id', collectionId);

            // 绑定媒体内容查看事件
            $('.view-media-item').on('click', function() {
                const mediaId = $(this).data('id');
                const mediaType = $(this).data('type');
                showMediaDetail(mediaId, mediaType); // 假设存在媒体详情查看函数
            });

        } catch (error) {
            // 显示错误信息
            $('#collectionDetailContent').html(`
                <div class="py-10 text-center">
                    <i class="fa fa-exclamation-circle text-danger text-xl mb-2"></i>
                    <p class="text-neutral-600">${error.message || '获取详情失败，请重试'}</p>
                    <button id="reloadDetailBtn" class="mt-3 px-4 py-1 bg-primary text-white rounded hover:bg-primary/90">
                        重新加载
                    </button>
                </div>
            `);

            // 绑定重新加载事件
            $('#reloadDetailBtn').on('click', () => showCollectionDetail(collectionId));
        }
    }
    
    // 显示认领模态框
    function showClaimModal(collectionId) {
        // 复用全局的claimModal
        $('#claimMessage').text(`您确定要认领合集 [${collectionId}] 吗？认领后其他审核员将无法操作。`);
        $('#claimModal').removeClass('hidden').addClass('flex');
        $('#confirmClaimBtn').data('id', collectionId);
    }
    
    // 显示通过模态框
    function showApproveModal(collectionId) {
        $('#modalTitle').text('审核通过确认');
        $('#modalMessage').text(`您确定要通过合集 [${collectionId}] 的审核吗？`);
        $('#batchInfo').addClass('hidden');
        $('#confirmModal').removeClass('hidden').addClass('flex');
        $('#confirmBtn').data('id', collectionId).data('action', 'approve');
    }
    
    // 显示拒绝模态框
    function showRejectModal(collectionId) {
        $('#rejectTypeSelect').val('');
        $('#rejectRemark').val('');
        $('#rejectModal').removeClass('hidden').addClass('flex');
        $('#confirmReject').data('id', collectionId);
    }

    // 隐藏拒绝模态框
    function hideRejectModal() {
        $('#rejectTypeSelect').val('');
        $('#rejectRemark').val('');
        $('#rejectModal').removeClass('flex').addClass('hidden');
        $('#confirmReject').data('id', '');
    }
    
    // 显示复查模态框
    function showReviewModal(collectionId) {
        $('#reviewRemark').val('');
        $('#reviewModal').removeClass('hidden').addClass('flex');
        $('#confirmReview').data('id', collectionId);
    }
    
    // 初始化审核操作事件
    function initAuditEvents() {
        // 确认认领
        $('#confirmClaimBtn').click(function() {
            const collectionId = $(this).data('id');
            $('#claimModal').removeClass('flex').addClass('hidden');
            
            // 模拟API请求
            showToast('正在认领合集...', 'info');
            setTimeout(() => {
                showToast('合集认领成功', 'success');
                initTableData(); // 重新加载表格数据
            }, 800);
        });
        
        // 取消认领
        $('#cancelClaimBtn').click(function() {
            $('#claimModal').removeClass('flex').addClass('hidden');
        });
        
        // 确认通过
        $('#confirmBtn').click(function() {
            const collectionId = $(this).data('id');
            const action = $(this).data('action');
            $('#confirmModal').removeClass('flex').addClass('hidden');
            
            // 模拟API请求
            showToast(`正在${action === 'approve' ? '通过' : '处理'}合集...`, 'info');
            setTimeout(() => {
                showToast(`合集${action === 'approve' ? '审核通过' : '操作成功'}`, 'success');
                initTableData(); // 重新加载表格数据
            }, 800);
        });
        
        // 取消操作
        $('#cancelBtn').click(function() {
            $('#confirmModal').removeClass('flex').addClass('hidden');
        });
        
        // 确认拒绝
        $('#confirmReject').click(function() {
            const collectionId = $(this).data('id');
            const rejectType = $('#rejectTypeSelect').val();
            const remark = $('#rejectRemark').val().trim();
            
            if (!rejectType) {
                showToast('请选择拒绝类型', 'warning');
                return;
            }
            
            $('#rejectModal').removeClass('flex').addClass('hidden');
            
            batchOperate(collectionId, 'reject')
                .then(() => {
                    initTableData(); // 重新加载列表
                    showToast('批量通过成功', 'success');
                })
                .catch(error => {
                    // console.error('批量认领失败:', error);
                    showToast('批量通过失败，请重试', 'error');
                });
        });
        
        // 关闭拒绝模态框
        $('#closeRejectModal, #cancelReject').click(function() {
            $('#rejectModal').removeClass('flex').addClass('hidden');
        });
        
        // 确认标记复查
        $('#confirmReview').click(function() {
            const collectionId = $(this).data('id');
            const remark = $('#reviewRemark').val().trim();
            
            $('#reviewModal').removeClass('flex').addClass('hidden');
            
            batchOperate(collectionId, 'review')
                .then(() => {
                    initTableData(); // 重新加载列表
                    showToast('标记复查成功', 'success');
                })
                .catch(error => {
                    // console.error('批量认领失败:', error);
                    showToast('标记复查失败，请重试', 'error');
                });
        });
        
        // 关闭复查模态框
        $('#closeReviewModal, #cancelReview').click(function() {
            $('#reviewModal').removeClass('flex').addClass('hidden');
        });
        
        // 从详情页进行审核操作
        $('#operateFromDetailBtn').click(function() {
            const collectionId = $(this).data('id');
            $('#collectionDetailModal').removeClass('flex').addClass('hidden');
            showApproveModal(collectionId);
        });
    }
    
    /**
     * 单个操作API调用
     */
    async function operateSingle(contentId, action) {
        try {
            let url = '';
            let requestData = { ids: [contentId] };

            switch(action) {
                case 'approve':
                    url = '/system/BatchAuditPass';
                    break;
                case 'reject':
                    url = '/system/BatchAuditReject';
                    // 获取拒绝类型（通过模态框）
                    const rejectType = $('#rejectTypeSelect').val();
                    if (!rejectType) {
                        throw new Error('请选择拒绝类型');
                    }
                    requestData.rejectType = rejectType;
                    requestData.remark = $('#rejectRemark').val().trim() || '';
                    break;
                case 'review':  // 添加复查操作支持
                    url = '/system/BatchClaimCollection';  // 假设的后端API地址
                    requestData.remark = $('#reviewRemark').val() || '';  // 可选备注
                    break;
                case 'claim':  // 添加认领操作支持
                    url = '/system/BatchClaim';  // 假设的后端API地址
                    requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                    break;
                default:
                    throw new Error('不支持的操作类型');
            }

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.message || `操作失败: ${response.statusText}`);
            }
            
            return result;
        } catch (error) {
            // console.error(`批量${action}操作失败:`, error);
            // throw error; // 抛出错误给调用方处理
            showToast(error.msg || '操作失败');
        }
    }
    /**
     * 批量操作通用方法
     * @param {Array} ids - 内容ID数组
     * @param {string} action - 操作类型(approve/reject)
     * @returns {Promise}
     */
    async function batchOperate(ids, action) {
        try {
            let url = '';
            let requestData = { ids: ids };

            switch(action) {
                case 'approve':
                    url = '/system/BatchAuditPassCollection';
                    break;
                case 'reject':
                    url = '/system/BatchAuditRejectCollection';
                    // 获取拒绝类型（通过模态框）
                    const rejectType = $('#rejectTypeSelect').val();
                    if (!rejectType) {
                        throw new Error('请选择拒绝类型');
                    }
                    requestData.rejectType = rejectType;
                    requestData.remark = $('#rejectRemark').val().trim() || '';
                    break;
                case 'review':  // 添加复查操作支持
                    url = '/system/BatchMarkReviewCollection';  // 假设的后端API地址
                    requestData.remark = $('#reviewRemark').val() || '';  // 可选备注
                    break;
                case 'claim':  // 添加认领操作支持
                    url = '/system/BatchClaimCollection';  // 假设的后端API地址
                    requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                    break;
                default:
                    throw new Error('不支持的操作类型');
            }

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 初始化批量操作事件
    function initBatchOperations() {
        // 批量认领
        $('#collectionBatchClaimBtn').click(function() {
            const checkedItems = $('.collection-item-checkbox:checked');
            const ids = Array.from(checkedItems).map(item => $(item).data('id'));
            
            if (ids.length === 0) {
                showToast('请选择要认领的记录');
                return;
            }
            
            // 调用后端API进行批量认领
            batchOperate(ids, 'claim')
                .then(() => {
                    initTableData(); // 重新加载列表
                    showToast('批量认领成功', 'success');
                })
                .catch(error => {
                    // console.error('批量认领失败:', error);
                    showToast('批量认领失败，请重试', 'error');
                });
        });
        
        // 批量通过
        $('#collectionBatchApproveBtn').click(function() {
            const checkedItems = $('.collection-item-checkbox:checked');
            const ids = Array.from(checkedItems).map(item => $(item).data('id'));
            // 调用后端API进行批量认领
            batchOperate(ids, 'approve')
                .then(() => {
                    initTableData(); // 重新加载列表
                    showToast('批量通过成功', 'success');
                })
                .catch(error => {
                    // console.error('批量认领失败:', error);
                    showToast('批量通过失败，请重试', 'error');
                });
        });
        
        // 批量拒绝
        $('#collectionBatchRejectBtn').click(function() {
            const checkedItems = $('.collection-item-checkbox:checked');
            const ids = Array.from(checkedItems).map(item => $(item).data('id'));
            if (ids.length === 0) {
                showToast('请选择要拒绝的记录', 'warning');
                return;
            }
            
            showRejectModal(ids);
        });
        
        // 批量标记复查
        $('#collectionBatchReviewBtn').click(function() {
            const checkedItems = $('.collection-item-checkbox:checked');
            const ids = Array.from(checkedItems).map(item => $(item).data('id'));
            if (ids.length === 0) {
                showToast('请选择要标记复查的记录', 'warning');
                return;
            }
            showReviewModal(ids);
        });
    }
    /**
     * 获取统计数据
     */
    async function getStatics() {        
        try {
            // 发起请求
            const response = await fetch(`/system/GetCollectionStats`, {
                method: 'GET',
                headers: {
                    // GET请求无需设置Content-Type（无请求体）
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) { // 更规范的状态判断
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const result = await response.json(); // 仅解析一次响应体
            const stats = result.data;

            if (!stats) {
                throw new Error('统计数据格式异常');
            }

            console.log(stats);

            // 更新待审核合集数据
            if (stats.pending) {
                $('#pendingCollections').text(stats.pending.total);
                const pendingTrend = stats.pending.trend;
                const pendingPercent = stats.pending.percent;
                const pendingTrendEl = $('#pendingCollections').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                pendingTrendEl.html(`
                    <i class="fa fa-arrow-${pendingTrend === 1 ? 'up' : pendingTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                    ${Math.abs(pendingPercent)}%
                `);
                pendingTrendEl.removeClass('text-success text-danger').addClass(
                    pendingTrend === 1 ? 'text-danger' : pendingTrend === -1 ? 'text-success' : 'text-neutral-400'
                );
            }

            // 更新今日已审核数据
            if (stats.audited) {
                $('#todayReviewed').text(stats.audited.total);
                const auditedTrend = stats.audited.trend;
                const auditedPercent = stats.audited.percent;
                const auditedTrendEl = $('#todayReviewed').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                auditedTrendEl.html(`
                    <i class="fa fa-arrow-${auditedTrend === 1 ? 'up' : auditedTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                    ${Math.abs(auditedPercent)}%
                `);
                auditedTrendEl.removeClass('text-success text-danger').addClass(
                    auditedTrend === 1 ? 'text-success' : auditedTrend === -1 ? 'text-danger' : 'text-neutral-400'
                );
            }

            // 更新已拒绝合集数据
            if (stats.rejected) {
                $('#rejectedCollections').text(stats.rejected.total);
                const rejectedTrend = stats.rejected.trend;
                const rejectedPercent = stats.rejected.percent;
                const rejectedTrendEl = $('#rejectedCollections').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                rejectedTrendEl.html(`
                    <i class="fa fa-arrow-${rejectedTrend === 1 ? 'up' : rejectedTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                    ${Math.abs(rejectedPercent)}%
                `);
                rejectedTrendEl.removeClass('text-success text-danger').addClass(
                    rejectedTrend === 1 ? 'text-danger' : rejectedTrend === -1 ? 'text-success' : 'text-neutral-400'
                );
            }

            // 更新平均审核时长数据
            if (stats.avgHandleTime) {
                $('#avgReviewTime').text(`${stats.avgHandleTime.minutes} 分钟`);
                const timeTrend = stats.avgHandleTime.trend;
                const timePercent = stats.avgHandleTime.percent;
                const timeTrendEl = $('#avgReviewTime').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                timeTrendEl.html(`
                    <i class="fa fa-arrow-${timeTrend === 1 ? 'up' : timeTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                    ${Math.abs(timePercent)}%
                `);
                timeTrendEl.removeClass('text-success text-danger').addClass(
                    timeTrend === 1 ? 'text-danger' : timeTrend === -1 ? 'text-success' : 'text-neutral-400'
                );
            }

            return result; // 返回解析后的完整结果

        } catch (error) {
            // 确保showToast已定义，否则替换为console.error
            if (typeof showToast === 'function') {
                showToast(error.message || '获取统计数据失败');
            } else {
                console.error(error.message || '获取统计数据失败');
            }
        }
    }
    
    // 页面初始化
    function init() {
        getStatics();
        initTableData();
        initCheckboxEvents();
        initFilterEvents();
        initActionEvents();
        initAuditEvents();
        initBatchOperations();
    }
    
    // 启动初始化
    init();
});